package com.example.finaltool.service;

import com.example.finaltool.annotations.Timer;
import com.example.finaltool.consts.Table;
import com.example.finaltool.consts.task.Task;
import com.example.finaltool.mapper.SysConfigMapper;
import com.example.finaltool.model.DepInfo;
import com.example.finaltool.model.config.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class SysConfigService {

    SysConfigMapper mapper;

    @Autowired
    public SysConfigService(SysConfigMapper mapper) {
        this.mapper = mapper;
    }

    @Timer(Table.SYS_CONFIG)
    @Transactional(rollbackFor = Exception.class)
    public void save(Data data, DepInfo info) {
        String corpId = data.getCorpId();
        List<String> existCunName = listCunNameOfZhen(corpId);
        info.getCunDepInfoList().stream().parallel().forEach(c -> {
            if (existCunName.contains(c.getCunName())) {
                log.info(c.getCunName() + " 已经保存过，不会保存这个村的 " + Table.SYS_CONFIG + " 信息");
            } else {
                Task.sysConfigTask(c).forEach(s -> mapper.save(s.getLabelId(), s.getConfigName(), s.getConfigKey(), s.getConfigValue(), s.getValueType(), corpId, c.getCunDepId()));
            }
        });
    }

    private List<String> listCunNameOfZhen(String corpId) {
        return mapper.getExist(corpId);
    }
}
